package com.hexiang.rocketmq.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQLocalRequestCallback;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RpcProducer {

    private static final String TOPIC_NAME = "RPC_HELLO_SPRING_TOPIC";

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送异步消息
     */
    public void asyncSendAndReceive(String msgBody) {
        rocketMQTemplate.sendAndReceive(TOPIC_NAME, MessageBuilder.withPayload(msgBody).build(), new RocketMQLocalRequestCallback<Message>() {
            @Override
            public void onSuccess(Message message) {
                try {
                    if (null != message) {
                        log.info("msg:{}", new String(message.getBody()));
                    }
                } catch (Exception e) {
                    log.error("err", e);
                }

            }

            @Override
            public void onException(Throwable e) {
                log.error("err", e);
            }
        }, 10000);
    }

    public void sendAndReceive(String msgBody) {
        Message respMessage = rocketMQTemplate.sendAndReceive(TOPIC_NAME, MessageBuilder.withPayload(msgBody).build(), Message.class, 5000);
        log.info("respMsg:{}", new String(respMessage.getBody()));

    }

}